package com.wl.boot.batch.util;

import org.ttzero.excel.reader.ExcelReader;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @author wanglu
 * @date 2021-06-15 15:28
 */
public class EECUtil {

    public static void main(String[] args) throws Exception {
        String fileName = "C:\\Users\\Administrator\\Desktop\\20W.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        long start = System.currentTimeMillis();
        System.out.println("开始解析：" + start);
        List<Object> list = streamRead(fileName);
        long end = System.currentTimeMillis();
        System.out.println("解析耗时：" + (end - start) / 1000);
        System.out.println("数据量：" + list.size());
    }

    public static List<Object> streamRead(String filePath) {
        List<Object> list = new ArrayList<>();
        try (ExcelReader reader = ExcelReader.read(Paths.get(filePath))) {
            int size = reader.sheet(0).getHeader().toString().split(" \\| ").length;
            reader.sheet(0).dataRows().forEach(row -> {
                        List<Object> temp = Arrays.asList(row.toString().split(" \\| "));
                        List<Object> datarow = new ArrayList<>(temp);
                        int csize = datarow.size();
                        if (datarow.size() != size) {
                            IntStream.range(0, size - csize).forEach(e -> {
                                datarow.add(null);
                            });
                        }
                        list.add(datarow);
                    }
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static List<Object> streamRead(InputStream in) {
        List<Object> list = new ArrayList<>();

        try (ExcelReader reader = ExcelReader.read(in)) {
            int size = reader.sheet(0).getHeader().toString().split(" \\| ").length;
            reader.sheet(0).dataRows().forEach(row -> {
                        List<Object> temp = Arrays.asList(row.toString().split(" \\| "));
                        List<Object> datarow = new ArrayList<>(temp);
                        int csize = datarow.size();
                        if (datarow.size() != size) {
                            IntStream.range(0, size - csize).forEach(e -> {
                                datarow.add(null);
                            });
                        }
                        list.add(datarow);
                    }
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
